package com.chidopi.cdf.aop;

import org.apache.commons.lang.time.StopWatch;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.chidopi.cdf.struts1actions.CdfDispatchAction;


@Aspect
@Component
public class Struts1Profiler {
	private static Logger logger = LoggerFactory.getLogger(Struts1Profiler.class);
//  @Pointcut("execution(public * com.chidopi.poc..*.*(..))")
	@Pointcut("target(com.chidopi.cdf.struts1actions.ICdfAction)")
	public void timer() {
		logger.info("call timer!!");
	}

	@Around("timer()")
	public Object time(ProceedingJoinPoint joinPoint) throws Throwable {
      String clazzName = joinPoint.getTarget().getClass().getSimpleName();
      String methodName = joinPoint.getSignature().getName();
      CdfDispatchAction action = null;
		try {
			action = (CdfDispatchAction) joinPoint.getTarget();
		} catch (Exception e) {
			logger.warn("Cast Error", e);
		}

      StopWatch clock = new StopWatch();
      clock.start();
      Object result = joinPoint.proceed();
      clock.stop();
      if (action != null) methodName = action.getMethodName();

      String[] params = new String[] { clazzName, methodName, clock.getTime() + "" };
      logger.info("[{}] Run [{}] method spent [{}] ms", params);
      return result;
	}
}
